# Copyright (c) 2022, hzmes and contributors
# For license information, please see license.txt

import frappe
from frappe.model.document import Document
from frappe.model.mapper import get_mapped_doc

class SRMInquiry(Document):
	def on_submit(self):
		for s in self.supplier_subs:
			# make_inquiry_of_supplier(self.name, s.supplier_number)
			self.make_inquiry_of_supplier(self.name, s.supplier_number, s.supplier_name, s.receive_email)


	# 生成供应商询价单，每个供应商一张单以隔离权限
	@frappe.whitelist()
	def make_inquiry_of_supplier(self, source_name, supplier, supplier_name, receive_person, target_doc=None):
		doc = get_mapped_doc(
			"SRM Inquiry",
			source_name,
			{
				"SRM Inquiry": {
					"doctype": "SRM Inquiry Of Supplier",
					"field_map": {"name": "from_inquiry"},
					"validation": {
						"docstatus": ["=", 1],
					},
				},
				"SRM Inquiry Material Sub": {
					"doctype": "SRM Inquiry Of Supplier Material Sub",
					"field_map": {
						"qty": "qty",
						"material_number": "material_number",
						"name": "from_inquiry_material_sub",
						"parent": "from_inquiry_material",
					},
					# "postprocess": update_item,
					# "condition": lambda doc: abs(doc.received_qty) < abs(doc.qty),
				},
			},
			target_doc,
			ignore_permissions=True
		)
		doc.supplier = supplier
		doc.supplier_name = supplier_name
		doc.receive_person = receive_person
		doc.insert(ignore_permissions=True)
		return doc


	# 从报价单中查询
	@frappe.whitelist()
	def get_data_from_srm_quotation(self, docname):
		# 包含要生成比价单的所有信息查询出来, 查询条件: 1. 是询价单下推的报价单; 2. 已经提交的报价单; 3. 跟该询价单关联的报价单记录
		sql = f"select t1.supplier_number, t1.supplier_name, t2.material_number, t2.material_name, t2.material_model, t2.price, t2.tax_price, t2.tax_rate, t2.name as row_name, t2.mpq, t2.moq, t2.lead_time  from `tabSRM Quotation` t1 join `tabSRM Quotation Material Sub` t2 on t1.name = t2.parent where t1.independent_quotation = 0 and t1.docstatus = 1 and t1.from_inquiry = '{docname}' order by t2.material_number, t2.price;"
		result = frappe.db.sql(sql,as_dict=1)
		return result